package com.health.viewscontrols.medical.device.fm;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.health.httpbean.model.FmModel;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tools.GlobalConts;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.novabluetooth.data.DeviceShowSaveData;
import com.peng.ppscalelibrary.BleManager.Interface.BleDataProtocoInterface;
import com.peng.ppscalelibrary.BleManager.Manager.MyBleManager;
import com.peng.ppscalelibrary.BleManager.Model.BleDeviceModel;
import com.peng.ppscalelibrary.BleManager.Model.BleEnum;
import com.peng.ppscalelibrary.BleManager.Model.BleUserModel;
import com.peng.ppscalelibrary.BleManager.Model.LFPeopleGeneral;
import com.peng.ppscalelibrary.BleManager.util.PPUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class FMQingActivity extends BaseDeviceActivity {

    MyBleManager bleManager;

    @Override
    public void startDevice() {
        bindingDevice();
    }

    @Override
    public void disconnectDevice() {

    }

    @Override
    public void doBusiness() {
        et_height.setVisibility(View.VISIBLE);
        tv_state.setText(com.nova.health.ble.R.string.fm_qj_tip);
        tv_operation_tips.setText(com.nova.health.ble.R.string.fm_qj);
    }

    @Override
    public void update(String hexStr) {

    }

    private void bindingDevice() {
        int height = 0;
        String heightStr = et_height.getText().toString().trim();
        if (!TextUtils.isEmpty(heightStr)) {
            try {
                height = Integer.parseInt(heightStr);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (height < 100 || height > 220) {
                ToastUtils.showLong("请输入100-220cm区间身高数据");
                return;
            }
        }

        showProgressDialog("正在测量体脂数据请稍后");
//        mDeviceName = "Health Scale";
        bleManager = MyBleManager.shareInstance(getApplication());
        List<BleDeviceModel> deviceList = new ArrayList<>();
        ARCHIVE_BASEINFO userInfo = NovaApplication.getUserInfo();
        String sex = userInfo.getSEX();
        int age = GlobalConts.getAge(userInfo.getBIRTHDAY());
        BleEnum.BleSex sexEnum;
        if ("DM01-08_1".equals(sex)) {
            sexEnum = BleEnum.BleSex.Male;
        } else {
            sexEnum = BleEnum.BleSex.Female;
        }
        BleUserModel userModel = new BleUserModel(height, age,
                sexEnum, BleEnum.BleUnit.BLE_UNIT_KG, 0);
        DeviceShowSaveData.saveCLData("手动输入",
                "手动输入", "身高",
                heightStr,
                "身高",
                UUID.randomUUID().toString(),
                NovaApplication.getUserInfo().getIDCARD(),
                TimeUtils.date2String(new Date(),"yyyy-MM-dd HH:mm:ss"));
        /**
         *  开始扫描蓝牙
         *
         * @param isBinding 是否是绑定设备，第一次扫描或不指定扫描设备时设置false, 扫描指定设备设置为true
         * @param deviceList 指定扫描设备列表 isBinging设置为true该方法生效
         * @param userModel 用户基本信息，包括身高、年龄、性别、重量单位（需要秤支持）
         * @param protocoInterface 扫描数据回调类
         */


        bleManager.searchDevice(true, deviceList, userModel, new BleDataProtocoInterface() {
            /**
             * 过程数据回调
             * @param bodyDataModel
             */
            @Override
            public void progressData(final LFPeopleGeneral bodyDataModel) {
                //过程数据回调
                String weightStr = PPUtil.getWeight(userModel.unit, bodyDataModel.lfWeightKg);
                Log.e(TAG, "progressData: " +  weightStr);
                tv_result.setVisibility(View.VISIBLE);
                tv_result.setText("测量过程体重：\n        " + weightStr + "kg");
            }

            /**
             * 锁定数据回调 （由于用户可能没有传入正缺范围内的身高性别等信息或者秤重过程中的一些别的原因（穿鞋，没踩到电极片等），
             * 锁定数据中只有体重和BMI的数据。）
             * @param bodyDataModel 测量结果
             * @param deviceModel   设备信息
             * @param isHeartRating 是否开始测量心率，true开始测量 false不测量或测量结束
             */
            @Override
            public void lockedData(LFPeopleGeneral bodyDataModel, BleDeviceModel deviceModel, boolean isHeartRating) {
                if (!isHeartRating) {
                    cancelProgressDialog();
                    showHealthScale(bodyDataModel);
                    if (bleManager != null) {
                        bleManager.stopSearch();
                    }
                }
            }

            /**
             * 历史数据回调， 在测量完成后，支持离线数据的秤会回调，不支持不回调
             *
             * @param isEnd 结束标志
             * @param bodyDataModel 存储数据的对象
             * @param date 时间 yyyy-MM-dd HH:mm:ss
             */
            @Override
            public void historyData(boolean isEnd, LFPeopleGeneral bodyDataModel, String date) {

            }

            /**
             * 蓝牙设备信息回调,在lockedData（）执行时回调
             * @param deviceModel
             */
            @Override
            public void deviceInfo(BleDeviceModel deviceModel) {

            }
        });
    }

    /**
     * 保存轻加体脂秤测量结果
     * @param bodyDataModel 体脂数据
     */
    private void showHealthScale(LFPeopleGeneral bodyDataModel) {
        String weightStr = PPUtil.getWeight(BleEnum.BleUnit.BLE_UNIT_KG, bodyDataModel.lfWeightKg);
        Log.e(TAG, "lockedData: " + bodyDataModel.toString() );
        if (weightStr.contains("kg")) {
            weightStr = weightStr.replace("kg","");
        }
        //保存体重
        DeviceShowSaveData.saveHealthScale(bodyDataModel,weightStr);
        tv_result.setText("获取测量结果成功： " + weightStr + " kg");

        DeviceShowSaveData.saveTizhong(weightStr + "");

        try {
            int height = 0;
            String heightStr = et_height.getText().toString().trim();
            if (!TextUtils.isEmpty(heightStr)) {
                height = Integer.parseInt(heightStr);
            }
            double bmi = calBMI(Double.parseDouble(weightStr), height);
            FmModel fmModel = new FmModel();
            fmModel.setHeight(height + "");
            fmModel.setWeight(weightStr + "");
            fmModel.setBmi(bmi + "");
            DeviceShowSaveData.getDataShow(GsonUtils.toJson(fmModel), "FM2");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public double calBMI(double weight, double height) {
        DecimalFormat df = new DecimalFormat("#.00");
        double newheight = height / 100;
        double v = weight / (newheight * newheight);
        String format = df.format(v);
        return Double.parseDouble(format);
    }
}
